<template>
    <canvas class="yzmBox" id="canvas" width="100" height="32" ref="canvas" @click="changYzm"></canvas>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';

// 使用defineEmits创建名称，接受一个数组
const emit = defineEmits(['getYzm'])
const canvas = ref()
//生成随机数
const rdm = (min: number, max: number): number => Math.floor(((Math.random() * (max - min)) + min))
let number1 = ref(0)
let number2 = ref(0)
const rdmColor = (min: number, max: number) => {
    let r = rdm(min, max)
    let g = rdm(min, max)
    let b = rdm(min, max)
    return `rgb(${r},${g},${b})`
}
//切换
const changYzm = () => {
    canvasYzm()
    emit('getYzm',number1.value+number2.value)
}
const canvasYzm = () => {
    //用canvas 画验证码
    const context = canvas.value.getContext('2d')
    let w = 100;
    let h = 32;
    // context.clearRect(0,0,w,h)
    // context.strokeRect(0, 0, 100, 32);
    //随机生成数
    number1.value = rdm(30, 50)
    number2.value = rdm(10, 20)
    context.font = rdm(10, 20) + "px bold 微软雅黑"
    context.fillStyle = rdmColor(0, 50)
    context.fillRect(0, 0, w, h)
    //保存画笔
    context.save()
    context.rotate(rdm(5, -5) * Math.PI / 180)
    context.fillStyle = rdmColor(50, 255)
    context.fillText(number1.value, 10, 23);
    context.fillStyle = rdmColor(50, 255)
    context.rotate(rdm(5, -5) * Math.PI / 180)
    context.fillText('+', 35, 23);
    context.fillStyle = rdmColor(50, 255)
    context.fillText(number2.value, 50, 23);
    context.fillStyle = rdmColor(50, 255)
    context.fillText('=', 77, 23);
    //恢复到原来位置  因为旋转会叠加
    context.restore()
    //随机干扰线
    for(let i=0;i<3;i++){
        context.beginPath()
        context.moveTo(rdm(0,w),rdm(0,h))
        context.lineTo(rdm(0,w),rdm(0,h))
        context.strokeStyle= rdmColor(150, 255)
        context.closePath()
        context.stroke()
    }
    //产生干扰点
    for(let i=0;i<10;i++){
        context.beginPath()
        context.arc(rdm(0,w),rdm(0,h),1,0,2*Math.PI)
        context.closePath()
        context.strokeStyle= rdmColor(200, 255)
        context.fill()
    }
}
onMounted(() => {
    canvasYzm()
    emit('getYzm',number1.value+number2.value)
    
})
</script>
<style lang='less'>
.yzmBox {
    width: 100px;
    height: 32px;
    overflow: hidden;
    cursor: pointer;
    border: 1px solid #ccc;
    border-radius: 5px;
}
</style>